package com.qilu.pe.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.History;
import com.qilu.pe.dao.bean.ImageUrl;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.GlobalReqUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.support.util.ViewUtil;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ToastUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MultipartBody;

// 患者信息录入
public class PatientInfoInputActivity extends Base2Activity {
    private RecyclerView rcv_history;
    private AppCompatEditText et_name, et_phone, et_sex, et_id;// , et_year, et_month, et_day
    private AppCompatEditText et_shrink, et_relax, et_special_info;
    private TextView tv_ok, tv_day;
    private RadioButton rb_1;
    private RelativeLayout rl_6, rl_header;// 选择日期,头像
    private TextView tv_name0, tv_phone0, tv_sex0, tv_birth0;
    private RoundedImageView iv_header;

    private String picture = "";// 图片的地址
    private String name, phone, sex, id, shrink, relax, specialInfo;// , year, month, day
    private String birth;

    private HistoryListAdapter adapter;
    private List<History> historyList = new ArrayList<>();
    private History currHis = new History();// 当前选择的病史

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_patient_info_input;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rcv_history = findViewById(R.id.rcv_history);
        et_name = findViewById(R.id.et_name);
        et_phone = findViewById(R.id.et_phone);
        et_sex = findViewById(R.id.et_sex);
        et_id = findViewById(R.id.et_id);
        et_shrink = findViewById(R.id.et_shrink);
        et_relax = findViewById(R.id.et_relax);
        et_special_info = findViewById(R.id.et_special_info);
        tv_ok = findViewById(R.id.tv_ok);
        tv_day = findViewById(R.id.tv_day);
        rb_1 = findViewById(R.id.rb_1);
        rl_6 = findViewById(R.id.rl_6);
        tv_name0 = findViewById(R.id.tv_name0);
        tv_phone0 = findViewById(R.id.tv_phone0);
        tv_sex0 = findViewById(R.id.tv_sex0);
        tv_birth0 = findViewById(R.id.tv_birth0);
        rl_header = findViewById(R.id.rl_header);
        iv_header = findViewById(R.id.iv_header);

        ViewUtil.setImportantText(tv_name0, "*患者姓名");
        ViewUtil.setImportantText(tv_phone0, "*手机号");
        ViewUtil.setImportantText(tv_sex0, "*性别");
        ViewUtil.setImportantText(tv_birth0, "*出生年月");

        GridLayoutManager manager = new GridLayoutManager(this, 3);
        adapter = new HistoryListAdapter(this);
        rcv_history.setLayoutManager(manager);
        rcv_history.setAdapter(adapter);

        setHeadTitle("信息录入");

        setListeners();

        reqMedicalHistoryList();
    }

    private void setListeners() {
        setOnClickListener(tv_ok, rl_6, rl_header);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_ok) {
            if (getAndVerifyInfo()) {
                hideProgress();
                reqAddPatient();
                showProgress();
            }
        }
        if (v == rl_6) {// 选择日期
            initTimePicker();
            pvTime.show();
        }
        if (v == rl_header) {// 上传头像
            chooseImage();
        }
    }

    private void chooseImage() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, 1901);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == 1901) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images.size() > 0) {
                    Logg.i("images.get(0).uri.getPath() = " + images.get(0).uri.getPath());
                    MultipartBody body = GlobalReqUtil.generateMultipartBody("id", new File(images.get(0).uri.getPath()));
                    GlobalReqUtil.reqUploadImage(body, new GlobalReqUtil.OnReqCallBack() {
                        @Override
                        public void onReqResult(BaseResult2<List<ImageUrl>> baseResult2) {
                            hideProgress();
                            if (baseResult2.isSuccess()) {
                                picture = baseResult2.getData().get(0).getImg();
                                GlideUtil.loadImg(Config.URL_IMG + picture, iv_header);
                            } else {

                            }
                            ToastUtils.showShort(baseResult2.getMsg());
                        }

                        @Override
                        public void onReqException(Throwable throwable) {
                            hideProgress();
                            throwable.printStackTrace();
                        }
                    });
                }
            } else {
                ToastUtils.showShort("没有数据");
            }
        }
    }

    private TimePickerView pvTime;

    private void initTimePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                birth = getTime(date);
                tv_day.setText(birth);
            }
        }).setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
            @Override
            public void onTimeSelectChanged(Date date) {
            }
        }).setType(new boolean[]{true, true, false, false, false, false})
                .isDialog(true) // 默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                })
                .setItemVisibleCount(7) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .setTitleText("选择时间")
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
        return format.format(date);
    }

    private boolean getAndVerifyInfo() {
        name = et_name.getText().toString().trim();
        phone = et_phone.getText().toString().trim();
        sex = rb_1.isChecked() ? "0" : "1";
        id = et_id.getText().toString().trim();
        shrink = et_shrink.getText().toString().trim();
        relax = et_relax.getText().toString().trim();
        specialInfo = et_special_info.getText().toString().trim();

        if (TextUtils.isEmpty(name)) {
            ToastUtils.showShort("请输入姓名");
            return false;
        }
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort("请输入手机号");
            return false;
        }
        if (TextUtils.isEmpty(sex)) {
            ToastUtils.showShort("请输入性别");
            return false;
        }
        if (TextUtils.isEmpty(id)) {
            ToastUtils.showShort("请输入身份证号");
            return false;
        }

        return true;
    }

    // 病史列表
    private Disposable reqMedicalHistoryList() {
        return APIRetrofit.getDefault().reqMedicalHistoryList()
                .compose(RxUtil.<BaseResult2<List<History>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<History>>>() {
                    @Override
                    public void accept(BaseResult2<List<History>> listBaseResult2) throws Exception {
                        hideProgress();
                        historyList = listBaseResult2.getData();
                        adapter.setDataList(historyList);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private StringBuffer subIdJsonArr;// 病史

    // 生成病史数据(格式:病史1,病史2)
    private void genMedicalIdData() {
        subIdJsonArr = new StringBuffer("");
        List<History> selHisList = new ArrayList<>();// 记录选中的病史信息
        for (int i = 0; i < historyList.size(); i++) {
            if (historyList.get(i).isSelect()) {
                selHisList.add(historyList.get(i));
            }
        }
        if (selHisList.size() >= 1) {
            for (int i = 0; i < selHisList.size(); i++) {
                if (i < selHisList.size() - 1) {
                    subIdJsonArr.append(selHisList.get(i).getId() + ",");
                } else {
                    subIdJsonArr.append(selHisList.get(i).getId());
                }
            }
        }
        subIdJsonArr.append("");
    }

    // 添加患者
    private Disposable reqAddPatient() {
        String blood = shrink + "-" + relax;

        genMedicalIdData();// 生成病史名称数据 使用","隔开
        String medical = subIdJsonArr.toString();

        return APIRetrofit.getDefault().reqAddPatient(Global.HEADER, name, phone, sex, birth, id
                , picture, blood, medical, specialInfo)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 result2) throws Exception {
                        hideProgress();
                        ToastUtils.showShort(result2.getMsg());
                        if (result2.isSuccess()) {
                            finish();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("患者添加失败");
                    }
                });
    }

    private class HistoryListAdapter extends ListBaseAdapter<History> {

        public HistoryListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_history_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            CheckBox cb_check = holder.getView(R.id.cb_check);
            TextView tv_name = holder.getView(R.id.tv_name);

            History h = mDataList.get(position);

            tv_name.setText(h.getName());

            if (h.isSelect()) {
                cb_check.setChecked(true);
            } else {
                cb_check.setChecked(false);
            }

            tv_name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    currHis = historyList.get(position);
                    historyList.get(position).setSelect(!historyList.get(position).isSelect());
                    adapter.setDataList(historyList);
                }
            });
            cb_check.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    currHis = historyList.get(position);
                    historyList.get(position).setSelect(!historyList.get(position).isSelect());
                    adapter.setDataList(historyList);
                }
            });

        }
    }
}